package com.woniuxy.login.controller;

import com.woniuxy.commons.utils.JWTUtil;
import com.woniuxy.commons.utils.ResStatus;
import com.woniuxy.commons.utils.ResponseResult;
import com.woniuxy.login.entity.Administrator;
import com.woniuxy.login.service.LoginService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author Waves
 * @date 2022/6/14 14:06
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Resource
    private LoginService loginService;

    @Resource
    private RedisTemplate redisTemplate;

    @GetMapping("/")
    public ResponseResult findByUsername(String username, String password, HttpServletResponse response){
        if(loginService.findByUsername(username,password).getCode() == 200){
            // 查询成功
            Administrator administrator = (Administrator)loginService.findByUsername(username, password).getData();

            // 生成token
            String token = JWTUtil.generateToken(administrator.getUsername());
            System.out.println("登录成功，开始生成token："+token);

            //生成refreshToken
            String refreshToken = UUID.randomUUID().toString();
            System.out.println("登录成功，开始生成refreshToken："+refreshToken);

            // 封装数据
            Map<String,Object> values = new HashMap<>();
            values.put("token",token);
            values.put("username", administrator.getUsername());

            // 将token放到redis
            redisTemplate.opsForHash().putAll(refreshToken,values);

            // 设置过期时间：用户在此时间段内不进行任何操作，下次再发送请求时就需要重新认证了
            redisTemplate.expire(refreshToken,60, TimeUnit.SECONDS);

            // 将refreshToken,token放到响应头，返回给前端
            response.setHeader("Authorization",token);
            response.setHeader("refreshToken",refreshToken);

            // 暴露头：为了能够在前端代码中能访问到token和refreshToken
            response.setHeader("Access-Control-Expose-Headers","Authorization,refreshToken");
            System.out.println("登陆成功");
            return new ResponseResult(
                    200,
                    "登录成功",
                    administrator,
                    ResStatus.SUCCESS
            );
        }
        System.out.println("登陆失败");
        return ResponseResult.Fail;
    }
}
